const {deleteData, update, add, page, list, detail, save, session, mlist, info, lists, query} = require("../../api/index.js")
const utils = require("../../utils/index.js")
Page({
    data: {
        title: '',
        user: {},
                pageIsAuth: false,
        token: '',
        baseURL: '',
        id: getApp().globalData.detailId,
        userId: getApp().globalData.userInfo.id,
        detailList: {},
        payAuth: "",
        picture: "",
                goodname: "",
                        shhf: '',
            sfshIndex: 0,
            sfshOptions: ['通过', '不通过', '待审核'],
            isAuth: '',
            isAuthFront: '',
            islike: false,
            thumbsupNumberShow: false,
            crazilyNumberShow: false,
            predetailList: "",
            commmentList: [],
        commentInput: '',
        userInfo: {},
        avatarurl: '',
        isThumbsup: false, // 本地点赞状态
        isCrazily: false, // 本地点踩状态
    },
    async onLoad(option) {
        let authobj = {}
                authobj['pageIsAuth'] = wx.getStorageSync('isAuth')
                        this.setData(authobj)
        let myid = option?.id ? option?.id : getApp().globalData.detailId;
        const user = wx.getStorageSync("userSession");
        // 读取本地点赞/点踩状态
        const isThumbsup = wx.getStorageSync('thumbsup_' + myid) || false;
        const isCrazily = wx.getStorageSync('crazily_' + myid) || false;
        this.setData({
            user,
            id: myid,
                isAuth: utils.isAuth('xiangmuchengguo', '审核'),
                isAuthFront: utils.isAuthFront('xiangmuchengguo', '审核'),
            token: wx.getStorageSync('token'),
            baseURL: wx.getStorageSync('baseURL') + '/'
            ,
            isThumbsup,
            isCrazily
        })
        // 获取用户信息和头像
        let userInfo = getApp().globalData.userInfo || wx.getStorageSync('userSession') || {};
        let avatarurl = userInfo.touxiang || wx.getStorageSync('avatarurl') || '';
        this.setData({ userInfo, avatarurl });
        await this.handleUpdateData()
    },
//立即预订
    orderTap() {
        if (this.data.activeSeat.length <= 0) {
            wx.showToast({
                title: '请选择需要预订的位置',
                icon: 'none'
            })
            return
        }
        const userInfo = getApp().globalData.userInfo
        const activeSeat = this.data.activeSeat.join(',') + ',' + this.data.detailList.selected
        let data = {
            orderid: this.createOrderId(),
            tablename: 'xiangmuchengguo',
            userid: userInfo.id,
            goodid: this.data.detailList.id,
            goodname: this.data.detailList.chengguomingcheng,
            buynumber: this.data.activeSeat.length,
            total: 0,
            discounttotal: 0,
            address: this.data.activeSeat,
            status: '已支付',
            discountprice: this.data.detailList.vipprice,
             picture: this.data.picture[0],
        }
        if (this.data.detailList?.price) {
            data['status'] = '未支付'
            data['price'] = this.data.detailList.price;
            data['total'] =wx.getStorageSync('vip') == '是'? 0 :
            parseFloat(this.data.detailList.price * this.data.activeSeat.length).toFixed(2)
            getApp().globalData.total = data.total;
            wx.showModal({
                title: '提示',
                content: '是否预订选中座位',
                complete: async (res) => {
                    if (res.confirm) {
                        wx.setStorageSync('orderGoods', [data])
                                                wx.navigateTo({
                            url: "/pages/shop-order/orders-confirm?type=1&seat=1"
                        })
                    }
                }
            })
        }

    }
    ,
        wxShare() {
            getApp().globalData.detailList = this.data.detailList;
            wx.setStorageSync('detailId', this.data.detailList.id)
        },
    chapterClick(e) {
        const item = e.currentTarget.dataset.item;
        const user = this.data.user;

        if (!this.data.userId) {
            wx.showToast({
                title: '请先登录',
                icon: "none"
            })
            setTimeout(() => {
                wx.navigateTo({
                    url: `/pages/login/login`,
                })
            }, 1500)
            return
        }
        let that = this.data;
    },
    authTap() {
        if (!this.data.token) {
            wx.showToast({
                title: '请先登陆',
                icon: 'none'
            })
            return
        }
    },
    async handleUpdateData() {
        let nowTable = wx.getStorageSync("nowTable");
        if (nowTable) {
            const res = await session(nowTable)
            if (res.code == 0) {
                getApp().globalData.userInfo = res?.data;
                let userId = res?.data.id;
                this.setData({
                    userId
                })
            }
        }

// 更新当前页面的数据
        var that = this;
        getApp().globalData.detailId == null ? getApp().globalData.detailId = wx.getStorageSync('detailId') : "";
        const id = getApp().globalData.detailId;
        if (id) {
            const {data} = await detail("xiangmuchengguo", id)
            this.setData({
                payAuthFront: utils.isAuthFront('xiangmuchengguo', '支付'),
                payAuth: utils.isAuth('xiangmuchengguo', '支付')
            })
                    data.shhf == null ? data.shhf = "" : ''
                    data.thumbsupNumber == null ? data.thumbsupNumber = 0 : ''
                    data.crazilyNumber == null ? data.crazilyNumber = 0 : ''
                const predetailList = Object.assign({}, data)
                this.setData({
                    predetailList
                })
            let objClo = {}
objClo['picture'] = data.tupian ?.split(',').map(item=>{
return  item.indexOf('http') !== -1?item: item = this.data.baseURL+item?.split(",")[0].replace('upload','flie');
});
    if(data.chengguoxiangqing){
        data.chengguoxiangqing = utils.addImgWidthStyle(data.chengguoxiangqing, '100%')
    }
                objClo['shhf'] = data.shhf;
            objClo['detailList'] = data;
            this.setData(objClo)
            // 设置导航栏标题为项目名称，背景为白色
            wx.setNavigationBarTitle({
                title: data.chengguomingcheng || ' '
            })
            wx.setNavigationBarColor({
                frontColor: '#000000',
                backgroundColor: '#ffffff',
                animation: {duration: 200, timingFunc: 'easeIn'}
            })
            if (!this.data.token) {
                return
            }
                await this.searchList("isStoreup")
                await this.searchList("isthumbsupb")
                await this.searchList("isCrazily")
        }
            const commentData = {
                page: 1,
                limit: 100,
                refid: getApp().globalData.detailId
            }
            const commentRes = await list("discussxiangmuchengguo", commentData);
// 评论数增加
            let detailList = this.data.detailList;
            detailList.discussNumber = commentRes.data.list.length;
            await update('xiangmuchengguo', detailList)
            commentRes.data.list = commentRes.data?.list.map((item) => {
                if(item.content){
                    item.content = utils.addImgWidthStyle(item.content, '60px')
                }
                return item
            })
            this.setData({
                commmentList: commentRes.data?.list,
                detailList
            })
        this.setData({
title: this.data.detailList.chengguomingcheng,
        });
    },

    onUnload: function () {
        getApp().globalData.detailList = {}
    },
                async addCommentap(content) {

            if (!this.data.token) {
                wx.showToast({ title: '请先登录', icon: 'none' });
                return;
            }
            // 兼容原有调用方式
            if (!content && this.data.commentInput) content = this.data.commentInput;
            if (!content) return;
            // 发送评论逻辑（伪代码，需根据实际API调整）
            // 假设有add/discussxiangmuchengguo接口
            const userInfo = this.data.userInfo;
            let commentData = {
                refid: this.data.id,
                userid: userInfo.id,
                nickname: userInfo.nickname || userInfo.nickName || '用户',
                avatarurl: userInfo.touxiang || this.data.avatarurl || '',
                content: content,
                addtime: new Date().toLocaleString()
            };
            try {
                await add('discussxiangmuchengguo', commentData);
                wx.showToast({ title: '评论成功', icon: 'success' });
                this.setData({ commentInput: '' });
                await this.handleUpdateData(); // 刷新评论区
            } catch (e) {
                wx.showToast({ title: '评论失败', icon: 'none' });
            }
        },
        onSendComment() {
            let content = this.data.commentInput;
            if (!content || !content.trim()) {
              wx.showToast({
                title: '请输入评论内容',
                icon: 'none'
              });
              return;
            }
            this.addCommentap(content);
        },
        onCommentInput(e) {
        this.setData({
            commentInput: e.detail.value
        });
        },
        async listAdd(anyType) {
            const userid = getApp().globalData.userInfo.id
            // 新增：先检查是否已收藏
            const searchData = {
                page: 1,
                limit: 1,
                refid: getApp().globalData.detailId,
                tablename: "xiangmuchengguo",
                userid,
                type: 1
            }
            const storeupRes = userid ? await list("storeup", searchData) : ''
            if (storeupRes?.data?.list?.length > 0) {
                wx.showToast({ title: '您已收藏过该成果', icon: 'none' })
                return
            }
            const data = {
                name: this.data.detailList.chengguomingcheng,
                picture: this.data.detailList.tupian,
                tablename: `xiangmuchengguo`,
                refid: getApp().globalData.detailId,
                userid,
                // type 收藏是1 关注是41
                type: anyType
            }
            await add("storeup", data)
        },
        async searchList(name) {
            const userid = getApp().globalData.userInfo.id
            const searchData = {
                page: 1,
                limit: 1,
                refid: getApp().globalData.detailId,
                tablename: "xiangmuchengguo",
                userid,
                    type: 1
            }
                if (name == "isStoreup") {

                    const storeupRes = userid ? await list("storeup", searchData) : ''
                    if (storeupRes?.data?.list?.length > 0) {
// 收藏
                        this.setData({
                            islike: true
                        })
                        const id = [storeupRes?.data?.list[0]?.id]
                        return id
                    } else {
                        this.setData({
                            islike: false
                        })
                    }
                }
                if (name == "isthumbsupb") {
                    searchData.type = "%2%"
                    const isthumbRes = userid ? await list("storeup", searchData) : ''
                    if (isthumbRes?.data?.list?.length > 0) {
                        this.setData({
// 点赞
                            thumbsupNumberShow: true,
                            crazilyNumberShow: false,
                        })
                        const id = [isthumbRes.data.list[0].id]
                        return id
                    } else {
                        this.setData({
                            thumbsupNumberShow: false
                        })
                    }
                }
                if (name == "isCrazily") {
                    searchData.type = "22"
                    const crazilyRes = userid ? await list("storeup", searchData) : ''
                    if (crazilyRes?.data?.list?.length > 0) {
// 踩
                        this.setData({
                            thumbsupNumberShow: false,
                            crazilyNumberShow: true
                        })
                        const id = [crazilyRes.data?.list[0].id]
                        return id
                    } else {
                        this.setData({
                            crazilyNumberShow: false,
                        })
                    }

                }
        },
        toggleLikeTap() {
            if (!this.data.token) {
                return
            }
            if (this.data.islike) {
                // 已收藏，执行取消收藏
                wx.showModal({
                    title: '提示',
                    content: '是否取消收藏',
                    complete: async (res) => {
                        if (res.confirm) {
                            const id = await this.searchList("isStoreup")
                            await deleteData('storeup', id)
                            await this.listUpdate('cancelislike')
                            this.searchList("isStoreup")
                        }
                    }
                })
            } else {
                // 未收藏，执行收藏
                wx.showModal({
                    title: '提示',
                    content: '是否收藏',
                    complete: async (res) => {
                        if (res.confirm) {
                            await this.listAdd(1)
                            await this.listUpdate('islike')
                            await this.searchList("isStoreup")
                        }
                    }
                })
            }
        },
        onThumbsupTap() {
            const { isThumbsup, isCrazily, id, detailList } = this.data;
            if (isThumbsup) {
                wx.setStorageSync('thumbsup_' + id, false);
                this.setData({
                    isThumbsup: false,
                    'detailList.thumbsupNumber': detailList.thumbsupNumber - 1
                });
            } else {
                wx.setStorageSync('thumbsup_' + id, true);
                wx.setStorageSync('crazily_' + id, false);
                this.setData({
                    isThumbsup: true,
                    isCrazily: false,
                    'detailList.thumbsupNumber': detailList.thumbsupNumber + 1,
                    'detailList.crazilyNumber': isCrazily ? detailList.crazilyNumber - 1 : detailList.crazilyNumber
                });
            }
        },
        onCrazilyTap() {
            const { isThumbsup, isCrazily, id, detailList } = this.data;
            if (isCrazily) {
                wx.setStorageSync('crazily_' + id, false);
                this.setData({
                    isCrazily: false,
                    'detailList.crazilyNumber': detailList.crazilyNumber - 1
                });
            } else {
                wx.setStorageSync('crazily_' + id, true);
                wx.setStorageSync('thumbsup_' + id, false);
                this.setData({
                    isCrazily: true,
                    isThumbsup: false,
                    'detailList.crazilyNumber': detailList.crazilyNumber + 1,
                    'detailList.thumbsupNumber': isThumbsup ? detailList.thumbsupNumber - 1 : detailList.thumbsupNumber
                });
            }
        },
        cancelCrazilynumTap() {

            if (!this.data.token) {
                return
            }
            wx.showModal({
                title: '提示',
                content: '是否取消点踩',
                complete: async (res) => {
                    if (res.confirm) {
                        const id = await this.searchList("isCrazily")
                        await deleteData('storeup', id)
                        await this.listUpdate("cancelCrazily")
                        await this.searchList("isCrazily")

                    }
                }
            })
        },
    async listUpdate(name) {
        const predetailList = this.data.predetailList
        const detailList = this.data.detailList
        predetailList.shangpintupian = this.data.picture[0]
        if (name == "thumbsupNumber") {
// 点赞
            predetailList.thumbsupNumber = predetailList.thumbsupNumber + 1
            detailList.thumbsupNumber = detailList.thumbsupNumber + 1
        }
        if (name == "cancelthumb") {
// 取消点赞
            predetailList.thumbsupNumber = predetailList.thumbsupNumber - 1
            detailList.thumbsupNumber = detailList.thumbsupNumber - 1
        }
        if (name == "crazilyNumber") {
            predetailList.crazilyNumber = predetailList.crazilyNumber + 1
            detailList.crazilyNumber = detailList.crazilyNumber + 1
        }
        if (name == "cancelCrazily") {
            predetailList.crazilyNumber = predetailList?.crazilyNumber - 1
            detailList.crazilyNumber = detailList.crazilyNumber - 1
        }
        if (name == 'cancelislike') {
            predetailList.storeupNumber = predetailList.storeupNumber - 1
            detailList.storeupNumber = detailList.storeupNumber - 1

        }
        if (name == "islike") {
            predetailList.storeupNumber = predetailList.storeupNumber + 1
            detailList.storeupNumber = detailList.storeupNumber + 1
        }
        this.setData({
            detailList
        })
        const resUpdate = await update('xiangmuchengguo', predetailList)
        if (resUpdate.code == 0) {
            this.setData({
                predetailList,
                "detailList.crazilyNumber": predetailList.crazilyNumber
            })

        }


    },
    previewImgTap(e) {
        var currentUrl = e.currentTarget.dataset.currenturl
        const list = this.data.picture.map(v => {
            return this.data.baseURL + v
        })
        wx.previewImage({
            urls: list, // 需要预览的图片链接列表
            current: currentUrl // 设置当前预览的图片
        });
                                                                                                                                    },


        onPayTap() {
        if (!wx.getStorageSync('token')) {
            wx.showToast({
                title: '请先登录',
                icon: "none"
            })
            setTimeout(() => {
                wx.navigateTo({
                    url: `/pages/login/login`
                })
            }, 1000)
            return
        }
            if (this.data.detailList.sfsh != '是') {
                wx.showToast({
                    title: '请审核通过后再操作',
                    icon: "none"
                })
                return
            }
        const baseURL = wx.getStorageSync('baseURL')
        let data = this.data.detailList
                                data["tupian"] = data.tupian
        data['buynumber'] = 1
        wx.setStorageSync('payObject', data);
        wx.setStorageSync('paytable', 'xiangmuchengguo');
        
                                wx.navigateTo({
            url: "/pages/pay-confirm/pay-confirm?type=1"
        })
    },
        onSHTap() {
            this.selectComponent('#bottomFrame').showFrame();
        },
        canlreply() {
            this.selectComponent('#bottomFrame').hideFrame();
        },
    async reply() {
        const detailList = this.data.detailList
                        detailList['shhf'] = this.data.shhf
                                                                                                                                                                const res = await update("xiangmuchengguo", detailList)
        if (res.code == 0) {
            setTimeout(function () {
                wx.showToast({
                    title: '回复成功',
                    icon: "none"
                })
            }, 1000)

            this.handleUpdateData()
        }
        this.selectComponent('#bottomFrame').hideFrame();
    },
async onShow() {
    },
                                        sfshChange(e) {
            var sfsh = '';
            this.data.sfshOptions[e.detail.value] == '通过' ? sfsh = '是' : (this.data.sfshOptions[e.detail.value] == '不通过' ? sfsh = '否' : this.data.sfshOptions[e.detail.value] == '待审核' ? sfsh = '待审核' : '')
            this.setData({
                sfshIndex: e.detail.value,
                'detailList.sfsh': sfsh
            })
        },
        onSHTap() {
            this.selectComponent('#bottomFrame').showFrame();
        },
//免费试读

// 下载
    download(e) {
        let url = e.currentTarget.dataset.url
        url = wx.getStorageSync('baseURL') + '/' + url;
        wx.downloadFile({
            url: url,
            success: (res) => {
                if (res.statusCode === 200) {
                    wx.showToast({
                        title: '下载成功',
                        icon: "none"
                    })

                    const filePath = res.tempFilePath
                    wx.openDocument({
                        filePath: filePath,
                        showMenu: true,
                        success: function (res) {
                            console.log('打开文档成功')
                        }
                    })
                    console.log('点击查看文件', filePath);
                                                                            }
            }
        });
    },
// 跨表
            async onAcrossTap(e) {

// (tableName,crossOptAudit,statusColumnName,tips,statusColumnValue)
        const info = e.currentTarget.dataset.info;
        const crossOptAudit = info.split(",")[1].replace(/'/g, '')

        const token = wx.getStorageSync("token")
        if (!this.data.token) {
                        wx.showToast({
                title: '请登录后再操作',
                icon: "none"
            })
            return
        }

            if (crossOptAudit == '是' && this.data.detailList?.sfsh != '是') {
                                wx.showToast({
                    title: '请审核通过后再操作',
                    icon: "none"
                })
                return
            }
        let pagetableName = info.split(",")[0]
        const statusColumnName = info.split(",")[2]
        const tips = info.split(",")[3]
        let statusColumnValue = info.split(",")[3]
        let type = info.split(",")[6];
        type ? type * 1 : type = 1;
        statusColumnValue = statusColumnValue.replace(/^'|'$/g, '');
        wx.setStorageSync('crossTable', 'xiangmuchengguo');
        wx.setStorageSync(`crossObj`, this.data.detailList);
        wx.setStorageSync('statusColumnName', statusColumnName?.substring(1, statusColumnName?.length - 1))
        wx.setStorageSync('tips', tips.substring(1, tips?.length - 1))
        let keyname = statusColumnValue?.split('[')[0]
        let statusColumnValueindex = statusColumnValue?.split('[')[1]?.replace(']', '')
        keyname = keyname ? keyname.replace('CrossSelect', '') : ''

        wx.setStorageSync('statusColumnValue', statusColumnValue)
        if (statusColumnName != '' && !statusColumnName.startsWith("[")) {
            var obj = this.data.detailList

            for (var o in obj) {
                if (statusColumnName.includes(o) && statusColumnValue == obj[o]) {
                    wx.showToast({
                        title: tips,
                        icon: "none"
                    })
                    return
                }
            }
        }
        getApp().globalData.detailId = this.data.detailList.id
        getApp().globalData.detailList = this.data.detailList
        wx.navigateTo({
            url: `/pages/${pagetableName}/update-and-add?cross=true`,
        })

    },
        
                                                                
})